package com.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.domain.*;
import com.example.result.JsonMap;
import com.example.result.JsonResult;
import com.example.service.AddressService;
import com.example.service.CartService;
import com.example.service.OrderService;
import com.example.service.Order_itemService;
import com.example.untils.MailUntils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.*;

@RestController
@RequestMapping("/order")
public class OrderController extends BaseController{
    @Autowired
    private OrderService orderService;
    @Autowired
    private Order_itemService order_itemService;
    @Autowired
    private AddressService addressService;
    @Autowired
    private CartService cartService;
    //添加订单
    @PostMapping("/insert/{aid}")
    public JsonResult insert(@RequestBody List<Long> cids,@PathVariable Long aid,HttpSession session){
        User user = getSessionUser(session);

        QueryWrapper<Address> addressWrapper=new QueryWrapper<>();
        addressWrapper.eq("aid",aid);
        Address address = addressService.getOne(addressWrapper);
        if(address==null){
            throw new RuntimeException("创建订单失败，无对应收货地址");
        }
        List<CartVO> listCids = cartService.getListCids(cids);
        if(listCids==null||listCids.size()==0){
            throw new RuntimeException("创建订单失败，无对应的购物车信息");
        }
        Long total_price=0L;
        for (CartVO cartVO : listCids) {
            total_price+=cartVO.getRealPrice();
        }
        //订单类的操作
        Order order=new Order();
        order.setUid(user.getUid());order.setRecv_name(address.getName());
        order.setRecv_phone(address.getPhone());
        order.setRecv_province(address.getProvince_name());
        order.setRecv_city(address.getCity_name());
        order.setRecv_area(address.getArea_name());
        order.setRecv_address(address.getAddress());
        order.setTotal_price(total_price);
        order.setStatus(0);
        order.setOrder_time(new Date());

        order.setCreated_user(user.getUsername());
        order.setCreated_time(new Date());
        order.setModified_user(user.getUsername());
        order.setModified_time(new Date());
        boolean flag1 = orderService.save(order);
        if(!flag1){
            throw new RuntimeException("创建订单失败");
        }
        for (CartVO cartVO : listCids) {
            total_price+=cartVO.getRealPrice();


        }
        //订单记录中的商品类的操作
        for (CartVO cartVO : listCids) {
            Order_item order_item=new Order_item();
            order_item.setOid(order.getOid());
            order_item.setPid(cartVO.getPid());
            order_item.setTitle(cartVO.getTitle());
            order_item.setImage(cartVO.getImage());
            order_item.setPrice(cartVO.getPrice());
            order_item.setNum(cartVO.getNum());
            order_item.setAfter_sale(0);
            order_item.setItem_status(0);
            order_item.setIs_receive(0);

            order_item.setCreated_user(user.getUsername());
            order_item.setCreated_time(new Date());
            order_item.setModified_user(user.getUsername());
            order_item.setModified_time(new Date());
            boolean flag2 = order_itemService.save(order_item);
            if(!flag2){
                throw new RuntimeException("创建订单失败");
            }
        }

        return new JsonResult(true,"订单创建成功",order.getOid());
    }
    //根据oid获取订单
    @GetMapping("/getOrderOid/{oid}")
    public JsonResult getOrderOid(@PathVariable Long oid){
        QueryWrapper<Order> wrapper=new QueryWrapper<>();
        wrapper.eq("oid",oid);
        Order order = orderService.getOne(wrapper);
        if(order==null){
            throw new RuntimeException("订单不存在");
        }

        return new JsonResult(true,"",order);
    }
    //更新表的status字段和支付时间
    @GetMapping("/updateStatus/{oid}")
    public JsonResult updateStatus(@PathVariable Long oid){
        QueryWrapper<Order> wrapper=new QueryWrapper<>();
        wrapper.eq("oid",oid);
        Order order = orderService.getOne(wrapper);
        if(order==null){
            throw new RuntimeException("订单不存在");
        }
        if(order.getStatus()==1){
            throw new RuntimeException("请不要重复支付");
        }
        if(order.getStatus()==2||order.getStatus()==3||order.getStatus()==4){
            throw new RuntimeException("您的订单已取消或已完成");
        }
        UpdateWrapper<Order> updateWrapper=new UpdateWrapper<>();
        updateWrapper.eq("oid",oid);
        updateWrapper.set("status",1);
        updateWrapper.set("pay_time",new Date());
        boolean flag = orderService.update(updateWrapper);
        if(!flag){
            throw new RuntimeException("支付失败");
        }
        return new JsonResult(true,"支付成功");
    }
    //根据oid获取订单列表
    @GetMapping("/getListoid")
    public JsonResult getListoid(Integer status,HttpSession session){
        Long uid = getSessionUId(session);
        QueryWrapper<Order> wrapper=new QueryWrapper<>();
        wrapper.eq("uid",uid);
        if(status!=null){
            wrapper.eq("status",status);
        }
        List<Order> orderList = orderService.list(wrapper);
        List<JsonMap> result=new ArrayList<>();
        for (Order order : orderList) {
            QueryWrapper<Order_item> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("oid",order.getOid());
            List<Order_item> order_itemList = order_itemService.list(queryWrapper);
            if(order_itemList==null){
                throw new RuntimeException("订单出现异常");
            }
            result.add(new JsonMap(order,order_itemList));

        }
        return new JsonResult(true,"",result);
    }
    @Autowired
    private JavaMailSender javaMailSender;

    //申请售后
    @GetMapping("/applyAfterSale/{id}")
    public JsonResult applyAfterSale(@PathVariable Long id){
        Order_item order_item = order_itemService.getById(id);

        if(order_item==null){
            throw new RuntimeException("订单商品有误,请刷新");
        }
        if(order_item.getAfter_sale()==1){
            throw new RuntimeException("您已申请此商品售后");
        }
        UpdateWrapper<Order_item> wrapper=new UpdateWrapper<>();
        wrapper.eq("id",id);
        wrapper.set("after_sale",1);
        boolean flag = order_itemService.update(wrapper);
        if(!flag){
            throw new RuntimeException("操作失败，请重试");
        }
        SimpleMailMessage message = MailUntils.sendAfterSale("2443329115@qq.com", "t_order_item表id为:" + id);
        javaMailSender.send(message);
        return new JsonResult(true,"申请成功");
    }
    //用户确认是否收货
    @GetMapping("/updateIs_receive/{id}")
    public JsonResult updateIs_receive(@PathVariable Long id){
        Order_item order_item = order_itemService.getById(id);
        if(order_item==null){
            throw new RuntimeException("订单商品有误,请刷新");
        }
        if(order_item.getIs_receive()==1){
            throw new RuntimeException("您已接受货物");
        }
        QueryWrapper<Order> qw3=new QueryWrapper<>();
        qw3.eq("oid",order_item.getOid());
        Order one = orderService.getOne(qw3);
        if(one.getStatus()==0){  //0-未支付，1-已支付，2-已取消，3-已关闭，4-已完成
            throw new RuntimeException("您还未支付,请支付");
        }
        if(one.getStatus()==2||one.getStatus()==3){  //0-未支付，1-已支付，2-已取消，3-已关闭，4-已完成
            throw new RuntimeException("您的订单已取消或已关闭!");
        }
        UpdateWrapper<Order_item> wrapper=new UpdateWrapper<>();
        wrapper.eq("id",id);
        wrapper.set("is_receive",1);
        boolean flag = order_itemService.update(wrapper);
        if(!flag){
            throw new RuntimeException("操作失败，请重试");
        }
        //通知售后
        SimpleMailMessage message = MailUntils.sendAfterSale("2443329115@qq.com", "t_order_item表id为:" + id);
        javaMailSender.send(message);
        //判断全部收货来完成订单
        QueryWrapper<Order_item> qw1=new QueryWrapper<>();
        qw1.eq("oid",order_item.getOid());
        List<Order_item> list = order_itemService.list(qw1);
        int is_receive=1;
        for (Order_item orderItem : list) {
            if(order_item.getIs_receive()==0){
                is_receive=0;
            }
        }
        if(is_receive==1){
            UpdateWrapper<Order> qw2=new UpdateWrapper<>();
            qw2.eq("oid",order_item.getOid());
            qw2.set("status",4);
            boolean update = orderService.update(qw2);
            if(!update){
                throw new RuntimeException("订单有误,请刷新");
            }
        }

        return new JsonResult(true,"操作成功");
    }
    //用户取消订单
    @GetMapping("/changeStatus/{oid}")
    public JsonResult changeStatus(@PathVariable Long oid){
        QueryWrapper<Order> wrapper1=new QueryWrapper<>();
        wrapper1.eq("oid",oid);
        Order order = orderService.getOne(wrapper1);
        if(order==null){
            throw new RuntimeException("订单信息不存在,请刷新");
        }
        UpdateWrapper<Order> wrapper2=new UpdateWrapper<>();
        wrapper2.eq("oid",oid);
        wrapper2.set("status",2);
        boolean flag = orderService.update(wrapper2);
        if(!flag){
            throw new RuntimeException("取消失败,请重试");
        }
        return new JsonResult(true,"操作成功");
    }
}
